import { _decorator, Component, Animation, AnimationClip } from "cc";
import { AnimState3 } from "./AnimState4";
import { WarroirStates } from "../../Test1/Enums/EnumPool";
const { ccclass, property } = _decorator;

@ccclass("AnimEvents4")
export class AnimEvents4 extends Component {
  @property
  anim: Animation;

  @property
  animMap: Map<string, AnimState3> = new Map();

  animationName = "AnimEvent4";
  stateClipMap: Map<string, string> = new Map();

  generateClip(state: AnimState3) {
    let clip = AnimationClip.createWithSpriteFrames(
      state.spriteFrameArray,
      state.frameRate
    );

    clip.name = state.clipName;
    clip.wrapMode = state.clipWrapMode;
    clip.duration = state.clipDuration;
    return clip;
  }

  initializedAnim(value: AnimState3) {
    this.anim = this.node.getComponent(Animation);
    this.anim.node = this.node;
    this.anim.name = this.animationName;
    this.anim.playOnLoad = true;

    this.anim.addClip(this.generateClip(value));
  }

  structuredAnimations() {
    for (const [key, value] of this.animMap.entries()) {
      this.initializedAnim(value);
      this.stateClipMap.set(key, value.clipName);
    }

    console.log("AnimEvent4-anim", this.anim);
    this.stateTransition();
  }

  stateTransition(state: string = WarroirStates.WARRIOR_IDLE) {
    const clipName = this.stateClipMap.get(state);

    switch (state) {
      case WarroirStates.WARRIOR_ATTACK:
        this.anim.crossFade(clipName, 0.3);
        this.anim.on(
          Animation.EventType.FINISHED,
          this.onAnimationFinished,
          this
        );
        break;
      case WarroirStates.WARRIOR_IDLE:
        this.anim.play(clipName);
        break;
      default:
        this.anim.play(WarroirStates.WARRIOR_IDLE);
    }
  }

  onAnimationFinished() {
    console.log("onAnimationFinished");
    this.stateTransition();
  }
}
